<?php


namespace App\Repositories;


use App\Exceptions\BasicException;

class MallProductRarityTagRepository
{
    public function addOrEditProductRarityTag($param)
    {
        $id = $param['id'] ?? 0;
        $rarityTagName = $param['rarity_tag_name'];
        $status = $param['status'];

        $nameExist = app('model_product_rarity_tag')->where('name', $rarityTagName)
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })->first();
        if ($nameExist) throw new BasicException(0, '标签名称已经存在');

        $data = [
            'name' => $rarityTagName,
            'status' => $status
        ];

        if ($id > 0) {
            $exist = app('model_product_rarity_tag')->select('id')->where('id', $id)->first();
            if (empty($exist)) throw new BasicException(0, '标签id错误');
            return app('model_product_rarity_tag')->where('id', $id)->update($data);
        } else {
            return app('model_product_rarity_tag')->insert($data);
        }
    }
}